package com.kkb.service.impl;

import com.kkb.dao.AccountDao;
import com.kkb.pojo.Account;
import com.kkb.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    @Override
    public void addAccount(Account newAccount) {

    }

    @Override
    public void deleteAccountById(Integer id) {
        this.accountDao.deleteAccountById(id);
    }

    @Override
    public void updateAccountByAccount(Account newAccount) {
        this.accountDao.updateAccountByAccount(newAccount);
    }

    @Override
    public Account findAccountById(Integer id) {
        Account accountById = this.accountDao.findAccountById(id);
        return accountById;
    }

    @Override
    public Account findAccountByName(String name){
        return this.accountDao.findAccountByName(name);
    }

    @Override
    public List<Account> findAccountsByName(String name) {
        return this.accountDao.findAccountsByName(name);
    }

    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
    @Override
    public List<Account> findAllAccounts() {
        return this.accountDao.findAllAccounts();
    }

    /*
     *  @params: source - 转出方
     *           target - 收款方
     *           money  - 金额
     * */
    @Override
    public void transferMoney(String source, String target, Double money) {
        // 获得转出方对象 and 收款方对象
        Account sourceAccount = this.accountDao.findAccountByName(source);
        Account targetAccount = this.accountDao.findAccountByName(target);
        // 更新Bead对象中的money
        sourceAccount.setMoney(sourceAccount.getMoney() - money);
        targetAccount.setMoney(targetAccount.getMoney() + money);
        // 执行更新操作
        this.accountDao.updateAccountByAccount(sourceAccount);
//        int i = 100/0;
        this.accountDao.updateAccountByAccount(targetAccount);
    }
}
